<template>
  <el-dialog
      title="修改信息"
      v-model="dialogVisibleEdit"
      width="800px"
      @close="resetFormData"
  >
    <el-form ref="EditDataForm" :model="EditData" label-width="120px">
      <el-form-item
          v-for="(value, key) in Edit_reportInfo"
          :key="key"
          :label="value.verbose_name"
          :prop="key">
        <component
            :is="inputComponentForType(value, key)"
            v-model="EditData[key]"
            v-bind="value.componentProps || {}"
        >
          <!-- 当组件为el-select时，渲染options -->
          <template v-if="inputComponentForType(value, key) === 'el-select'">
            <el-option
                v-for="option in value.choices"
                :key="option"
                :label="option"
                :value="option"
            ></el-option>
          </template>
        </component>
      </el-form-item>
      <el-form-item label="相关人员">
        <div v-for="(author, index) in EditData['authors']" :key="index">
          ({{ author.role }})_{{ author.account }}__{{}}
        </div>
        <el-button @click="addAuthor">添加人员</el-button>
        <el-button @click="delAuthor">删除人员</el-button>
      </el-form-item>
      <el-form-item label="分数权重">
        <div>
          {{ EditData['score_weights'] }}
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   :loading="SubmitEditLoading"
                   :disabled="SubmitEditLoading"
                   @click="handleSubmitEdit">{{ SubmitEditLoading ? '正在添加' : '确认' }}
        </el-button>
        <el-button @click="dialogVisibleEdit = false">取 消</el-button>
      </el-form-item>
    </el-form>

  </el-dialog>

  <AddAuthor ref="EditAuthorComponent" :Type="'edit'"/>
</template>
<script setup>
import {ref, onMounted, watchEffect, onBeforeUnmount, reactive} from 'vue';
import setting from '@/setting.js';
import eventBus from "@/event-bus.js";
import {ElMessage} from "element-plus";
import AddAuthor from "@/components/Main/ReportManagement/AddAuthor.vue";
import global, {jsonApi} from "@/global.js";


const props = defineProps({
  tableType: {
    type: String,
    required: true
  },
  isAdmin: {
    type: Boolean,
    required: true
  }
});

const accessToken = localStorage.getItem('access_token');
const refreshToken = localStorage.getItem('refresh_token');
const SubmitEditLoading = ref(false);
const reportInfo = ref({});
const Edit_reportInfo = ref({});
const storedReportInfo = localStorage.getItem('reportinfo');
// 添加数据弹窗控制
const dialogVisibleEdit = ref(false);
let EditData = reactive({});
const EditDataForm = ref(null);
onMounted(() => {
  eventBus.on('report-form-table-edit', handleReportFormTableEdit);
  eventBus.on('author-edit', handleReportFormTableAuthorsEdit);
});

onBeforeUnmount(() => {
  eventBus.off('report-form-table-edit', handleReportFormTableEdit);
  eventBus.off('author-edit', handleReportFormTableAuthorsEdit);
});
const emit = defineEmits(['refresh-table']);

function refresh() {
  emit('refresh-table', {});
}

const handleSubmitEdit = async () => {
  SubmitEditLoading.value = true;
  // 在此处实现添加数据的逻辑
  console.log('添加数据的逻辑在这里实现');
  //去除this.newData.author中元素为空的元素
  EditData['Report'] = props.tableType;
  try {
    // 尝试使用当前的access_token获取数据
    let api_url = '';
    if (props.isAdmin) {
      api_url = '/reportmanager/updateforadmin/';
    } else {
      api_url = '/reportmanager/update/';
    }

    const response = await jsonApi(api_url, JSON.stringify(EditData));
    const data = await response.json();

    if (response.status === 201 || response.status === 200) {
      SubmitEditLoading.value = false;
      dialogVisibleEdit.value = false;
      refresh();
    } else {
      ElMessage({
        type: 'error',
        message: '添加失败: ' + data.error,
      });
      SubmitEditLoading.value = false;

    }

    // 如果没有错误，则返回数据


  } catch (error) {
    // 网络错误或其他非token导致的错误
    ElMessage({
      type: 'error',
      message: '添加失败 : ' + error.message,
    });
    SubmitEditLoading.value = false;
    throw error;
  }
}
// Methods
const getReportInfo = async () => {
  reportInfo.value = JSON.parse(storedReportInfo)[props.tableType];
  //获取增加时的字段
  Edit_reportInfo.value = reportInfo.value;
  const Edit_excludeFields = ['id', 'model_name', 'max_score', 'authors', 'score_weights', 'score', 'modified_time', 'attachment', 'reviewer', 'revstatus', 'created_time', 'review_time','input_info'];
  Edit_excludeFields.forEach(field => {
    // 如果报告信息中存在要排除的字段，则删除它
    if (Edit_reportInfo.value.hasOwnProperty(field)) {
      delete Edit_reportInfo.value[field];
    }
  });
  for (let key in Edit_reportInfo.value) {
    EditData[key] = null;
  }
  EditData['id'] = -1;
  EditData['authors'] = [];
  EditData['score_weights'] = [];


}
const handleReportFormTableEdit = (info) => {
  dialogVisibleEdit.value = true;
  getReportInfo()
  for (let key in EditData) {
    EditData[key] = info.EditData[key];
  }
  EditData['id'] = info.ID;
};
const handleReportFormTableAuthorsEdit = (info) => {
  //去除info中key为name的项
  const userinfoString = localStorage.getItem('userinfo')
  const userinfo = JSON.parse(userinfoString);
  if (EditData['authors'].length === 0) {
    if (props.isAdmin) {
      if (info.role !== '负责人') {
        ElMessage({
          type: 'error',
          message: '第一位只能是负责人，已修改'
        });
      }
      EditData['authors'].push({"name": info.name, "account": info.account, "role": "负责人"});
    } else {
      if (info.role !== '负责人' || info.account !== userinfo['username']) {
        ElMessage({
          type: 'warning',
          message: '你必须添加自己为第一顺位，且为负责人，已经帮您修改'
        });
      }
      EditData['authors'].push({"name": userinfo['name'], "account":  userinfo['username'], "role": "负责人"});

    }

    EditData['score_weights'].push(Number(info.weight));
  } else {
    if (info.role === '负责人') {
      ElMessage({
        type: 'error',
        message: '只能添加一个负责人'
      });
      //addData['score_weights']的和大于1
    } else if (EditData['score_weights'].reduce((a, b) => a + b, 0) > 1) {
      ElMessage({
        type: 'error',
        message: '分数权重之和不能大于1'
      });
    } else if (EditData['authors'].some(item => item.account === info.account)) {
      ElMessage({
        type: 'error',
        message: '不能添加重复的作者'
      });
    } else {
      EditData['authors'].push({"name": info.name, "account": info.account, "role": info.role});
      EditData['score_weights'].push(Number(info.weight));
    }

  }
};
const EditAuthorComponent = ref(null);
const addAuthor = () => {
  if (EditAuthorComponent.value && typeof EditAuthorComponent.value.open === 'function') {
    EditAuthorComponent.value.open(props.isAdmin, EditData['authors']);
  } else {
    console.error('addAuthorComponent.open is not a function');
  }
};
const delAuthor = () => {
  // if (EditData['authors'].length === 1) {
  //   ElMessage({
  //     type: 'warning',
  //     message: '至少需要一个作者'
  //   });
  //   return;
  // }
  EditData['authors'].pop();
  EditData['score_weights'].pop();
};
const inputComponentForType = (value, key) => {
  const componentMap = {
    'CharField': 'el-input',
    'IntegerField': 'el-input',
    'DateTimeField': 'el-date-picker',
    'JSONField': 'el-textarea', // 使用文本域展示JSON字符串，并考虑设置为只读
    'BooleanField': 'el-switch',
    'URLField': 'el-input',
    'TextField': 'el-input'
  };

  // 如果value.choices存在，则返回el-select组件并且附带options
  if (value.choices !== null) {
// 使用choice.label作为label，choice.value作为value
//     console.log(value.choices,value)
    return 'el-select'
  } else {
    // 直接返回组件类型，如果未找到则返回'未知类型'
    return componentMap[value.type] || 'el-input';
  }


};
// 重置表单数据
const resetFormData = () => {
  Object.keys(EditData).forEach(key => {
    if (EditData[key] instanceof File) {
      EditData[key] = null;
    } else {
      EditData[key] = '';
    }
  });
};


function showError(message, error, duration) {
  console.error(message, error);
  // 实现错误展示逻辑，例如使用通知组件
}
</script>
<style scoped>

</style>